﻿using System.Diagnostics;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using sixgod.Model.Attribute;

namespace sixgod.Common.DI
{
    public static class ServiceHelper
    {
        public static void AddServices(this IServiceCollection service)
        {
            var dll = DependencyContext.Default.RuntimeLibraries.Where(r => r.Name.StartsWith("sixgod.Service"))
                .Select(r => Assembly.Load(new AssemblyName(r.Name)));
            Console.WriteLine("正在注入服务···");
            var count = 0;
            foreach (var assembly in dll)
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.GetCustomAttribute<DiAttribute>() is null)
                    {
                        continue;
                    }

                    var di = type.GetCustomAttribute<DiAttribute>();
                    service.Add(new ServiceDescriptor(di.InterFaceType, type, di.ServiceLifetime));
                    count++;
                }
            }

            Console.WriteLine($"共注入服务{count}项");
        }
    }
}